package com.mida.dms.knw.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mida.dms.knw.Result.BaseResult;
import com.mida.dms.knw.entity.KnwCommonWordsTree;
import com.mida.dms.knw.entity.KnwCompositeInstance;
import com.mida.dms.knw.entity.KnwCompositeInstanceShortcut;
import com.mida.dms.knw.entity.KnwNarrativeBlock;
import com.mida.dms.knw.entity.vo.KnwCompositeInstanceDto;
import com.mida.dms.knw.mapper.KnwCommonWordsTreeMapper;
import com.mida.dms.knw.mapper.KnwCompositeInstanceMapper;
import com.mida.dms.knw.mapper.KnwCompositeInstanceShortcutMapper;
import com.mida.dms.knw.mapper.KnwNarrativeBlockMapper;
import com.mida.dms.knw.service.KnwCompositeInstanceService;
import com.mida.dms.knw.service.SoidService;
import com.mida.dms.knw.vo.KnwCompositeInstanceVo;
import com.mida.dms.knw.vo.KnwCompositeTmpVo;
import com.mida.dms.knw.vo.Page;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import com.mida.tool.common.utils.CharTransFormUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * KnwCompositeInstanceService
 */
@Slf4j
@Service
@Transactional
public class KnwCompositeInstanceServiceImpl extends BaseResult implements KnwCompositeInstanceService {

    public static final long STATUS = 149l;
    public static final long IS_DELETE = 0l;
    private static final int ONE = 1;
    private static final int TWO = 2;
    private static final int THREE = 3;
    public static final long SHORTCUT_TYPE = 35076626068799488L;
    /**
     * 复合实例Mapper
     */
    @Autowired
    private KnwCompositeInstanceMapper knwCompositeInstanceMapper;

    /**
     * 复合实例助记码Mapper
     */
    @Autowired
    private KnwCompositeInstanceShortcutMapper knwCompositeInstanceShortcutMapper;

    /**
     * soidService
     */
    @Autowired
    private SoidService soidService;



    @Autowired
    private KnwNarrativeBlockMapper knwNarrativeBlockMapper;


    @Autowired
    private KnwCommonWordsTreeMapper knwCommonWordsTreeMapper;



    /**
     * 保存复合实例
     *
     * @param knwCompositeInstanceVo
     * @throws Exception
     */
    @Override
    public ActionResult add(KnwCompositeInstanceVo knwCompositeInstanceVo) {
        ActionResult actionResult = new ActionResult();
        try {
            KnwCompositeInstance knwCompositeInstance = setKnwCompositeInstance(knwCompositeInstanceVo);
            KnwCompositeInstanceShortcut knwCompositeInstanceShortcut = setKnwCompositeInstanceShortcut(knwCompositeInstanceVo);
            Integer serialNo;
            serialNo = knwCompositeInstanceMapper.getMaxSerialNo(knwCompositeInstanceVo.getCommonWordsTreeSoid());
            if (serialNo == null || serialNo == 0) {
                knwCompositeInstance.setSerialNo(1);
            }  else if (serialNo > 0) {
                knwCompositeInstance.setSerialNo(serialNo+1);
            }

            Long soid = soidService.getSoid();
            knwCompositeInstance.setCompositeInstanceSoid(soid);
            knwCompositeInstanceShortcut.setCompositeInstanceSoid(soid);
            Long compositeInstanceShortcutSoid = soidService.getSoid();
            knwCompositeInstanceShortcut.setCompositeInstanceShortcutSoid(compositeInstanceShortcutSoid);

            soidService.insertOid(soid, 1);
            knwCompositeInstanceMapper.insertSelective(knwCompositeInstance);
            knwCompositeInstanceShortcutMapper.insertSelective(knwCompositeInstanceShortcut);
            //todo 维护叙述块表
            this.addNarrativeBlock(knwCompositeInstanceVo,soid,ONE);
            buildActionSuccess(actionResult);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            actionResult.setMessage("保存复合实例处理失败");
            return actionResult;
        }

        return actionResult;
    }

    /**
     * 更新复合实例
     *
     * @param vo
     * @throws Exception
     */
    @Override
    public ActionResult update(KnwCompositeInstanceVo vo) {
        ActionResult actionResult = new ActionResult();
        try {
            KnwCompositeInstance knwCompositeInstance = new KnwCompositeInstance();
            knwCompositeInstance.setCompositeInstanceSoid(vo.getCompositeInstanceSoid());
            knwCompositeInstance.setCompositeInstanceName(vo.getCompositeInstanceName());
            knwCompositeInstance.setNarrativeBlock(vo.getNarrativeBlock());
            knwCompositeInstance.setBusinessUnitSoid(vo.getBusinessUnitSoid());
            knwCompositeInstance.setOrgInfoSoid(vo.getOrgInfoSoid());
            knwCompositeInstance.setUpdateUser(vo.getCreator());
            knwCompositeInstance.setUpdateDate(new Date());
            if (StringUtils.isNotEmpty(knwCompositeInstance.getCompositeInstanceName())) {
                knwCompositeInstance.setPyCode(
                        CharTransFormUtil.toPinyinSimple(knwCompositeInstance.getCompositeInstanceName()));
                knwCompositeInstance.setWbCode(
                        CharTransFormUtil.toWubi(knwCompositeInstance.getCompositeInstanceName()));
            }

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("usContent", vo.getUsContent());
            map.put("usDiagnosis", vo.getUsDiagnosis());
            JSONObject json = new JSONObject(map);
            knwCompositeInstance.setNarrativeBlock(json.toString());

            knwCompositeInstanceMapper.updateByPrimaryKeySelective(knwCompositeInstance);

            KnwCompositeInstanceShortcut knwCompositeInstanceShortcut
                    = knwCompositeInstanceShortcutMapper.selectByCompositeInstanceSoid(vo.getCompositeInstanceSoid());

            if (knwCompositeInstanceShortcut != null) {
                if (StringUtils.isNotEmpty(knwCompositeInstance.getCompositeInstanceName())) {
                    knwCompositeInstanceShortcut.setShortcut(
                            CharTransFormUtil.toPinyinSimple(knwCompositeInstance.getCompositeInstanceName()));
                }
            }
            knwCompositeInstanceShortcut.setUpdateUser(vo.getCreator());
            knwCompositeInstanceShortcut.setUpdateDate(new Date());
            knwCompositeInstanceShortcutMapper.updateByPrimaryKeySelective(knwCompositeInstanceShortcut);
            //TODO 维护叙述块表
            this.addNarrativeBlock(vo,vo.getCompositeInstanceSoid(),TWO);
            buildActionSuccess(actionResult);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            actionResult.setMessage("保存复合实例处理失败");
            return actionResult;
        }

        return actionResult;
    }

    /**
     * 删除复合实例
     *
     * @param vo
     * @throws Exception
     */
    @Override
    public ActionResult delete(KnwCompositeInstanceVo vo) {
        ActionResult actionResult = new ActionResult();
        knwCompositeInstanceMapper.deleteByPrimaryKey(vo.getCompositeInstanceSoid());
        knwCompositeInstanceShortcutMapper.deleteByCompositeInstanceSoid(vo.getCompositeInstanceSoid());
        //TODO 维护叙述块表
        this.addNarrativeBlock(vo,vo.getCompositeInstanceSoid(),THREE);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    /**
     * 分页查询
     *
     * @param vo
     * @return
     */
    @Override
    public PageResultVo<KnwCompositeInstanceDto> getKnwCompositeInstancePage(KnwCompositeInstanceVo vo) {
        log.info("开始分页查询,查询条件:" + vo.toString());
        PageResultVo pageResultVo = new PageResultVo();
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwCompositeInstanceDto> list = new ArrayList<KnwCompositeInstanceDto>();
        try {
            Map<String, Object> mapParm = new HashMap<String, Object>();
            Page page = new Page();
            page = new Page(vo.getCurrentPage(), vo.getPageSize());

            mapParm.put("seachParm", vo.getSearchData());
            mapParm.put("commonWordsTreeSoid", vo.getCommonWordsTreeSoid());
            int num = knwCompositeInstanceMapper.getPageCount(mapParm);

            if (num == 0) {
                pageResultVo.setList(null);
                pageResultVo.setPage(null);
            } else {
                page.setTotalCount(num);
                mapParm.put("startIndex", page.getBeginIndex());
                mapParm.put("endIndex", vo.getCurrentPage() * page.getEveryPage());
                list = knwCompositeInstanceMapper.getKnwCompositeInstancePage(mapParm);

                pageResultVo.setList(list);
                pageResultVo.setPage(page);
            }
            return pageResultVo;


        } catch (Exception e) {
            list = new ArrayList<KnwCompositeInstanceDto>(0);
            pageResultVo.setList(list);
            log.error("复合实例分页查询异常", e);
            return pageResultVo;
        } finally {
            st.stop();
            log.info("本次分页查询耗时:" + st.getTime() + "ms");
        }
    }

    /**
     * 设置复合数据
     *
     * @param
     */
    private KnwCompositeInstance setKnwCompositeInstance(
            KnwCompositeInstanceVo vo) throws Exception {
        KnwCompositeInstance knwCompositeInstance = new KnwCompositeInstance();
        BeanUtils.copyProperties(vo, knwCompositeInstance);
        if (StringUtils.isNotEmpty(knwCompositeInstance.getCompositeInstanceName())) {
            knwCompositeInstance.setPyCode(
                    CharTransFormUtil.toPinyinSimple(knwCompositeInstance.getCompositeInstanceName()));
            knwCompositeInstance.setWbCode(
                    CharTransFormUtil.toWubi(knwCompositeInstance.getCompositeInstanceName()));
        }

       // Map<String, Object> map = new HashMap<String, Object>();
      //  map.put("usContent", vo.getUsContent());
      //  map.put("usDiagnosis", vo.getUsDiagnosis());
      //  JSONObject json = new JSONObject(map);
      //  knwCompositeInstance.setNarrativeBlock(json.toString());
        knwCompositeInstance.setCreator(vo.getCreator());
        knwCompositeInstance.setIsDelete(IS_DELETE);
        knwCompositeInstance.setStatus(STATUS);
        knwCompositeInstance.setCreateDate(new Date());
        return knwCompositeInstance;
    }




    /**
     * 设置复合数据数据
     *
     * @param
     */
    private KnwCompositeInstanceShortcut setKnwCompositeInstanceShortcut(
            KnwCompositeInstanceVo vo) throws Exception {
        KnwCompositeInstanceShortcut knwCompositeInstanceShortcut = new KnwCompositeInstanceShortcut();
        if (StringUtils.isNotEmpty(vo.getCompositeInstanceName())) {
            knwCompositeInstanceShortcut.setShortcut(
                    CharTransFormUtil.toPinyinSimple(vo.getCompositeInstanceName()));
            knwCompositeInstanceShortcut.setShortcutType(SHORTCUT_TYPE);
        }
        knwCompositeInstanceShortcut.setCreator(vo.getCreator());
        knwCompositeInstanceShortcut.setStatus(STATUS);
        knwCompositeInstanceShortcut.setIsDelete(IS_DELETE);
        knwCompositeInstanceShortcut.setCreateDate(new Date());
        return knwCompositeInstanceShortcut;
    }


    @Override
    public ActionResult updateSort(List<KnwCompositeInstanceVo> knwCompositeInstanceVoList) {
        ActionResult actionResult = new ActionResult();
        knwCompositeInstanceMapper.updateSoid(knwCompositeInstanceVoList);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    /**
     * 列表查询
     *
     * @param
     * @return
     */
    @Override
    public List<KnwCompositeInstanceDto> getKnwCompositeInstanceList(KnwCompositeInstanceVo vo) {
        log.info("开始列表查询,查询条件:" + vo.toString());
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwCompositeInstanceDto> list =
                new ArrayList<KnwCompositeInstanceDto>();
        try {
            Map<String, Object> mapParm = new HashMap<String, Object>();
            mapParm.put("commonWordsTreeSoid", vo.getCommonWordsTreeSoid());
            list = knwCompositeInstanceMapper.getKnwCompositeInstanceList(mapParm);
        } catch (Exception e) {
            list = new ArrayList<KnwCompositeInstanceDto>(0);
            log.error("列表查询查询异常"+e.getMessage(), e);
            return list;
        } finally {
            st.stop();
            log.info("本次列表查询耗时:" + st.getTime() + "ms");
        }

        return list;
    }

    @Override
    @Transactional
    public ActionResult enableKnwCompositeInstance(KnwCompositeInstanceVo knwCompositeInstanceVo) {
        ActionResult actionResult = new ActionResult();
        List<Long> compositeInstanceSoids = knwCompositeInstanceVo.getCompositeInstanceSoids();
        Long commonWordsTreeSoid = knwCompositeInstanceVo.getCommonWordsTreeSoid();
        Long status = knwCompositeInstanceVo.getStatus();
        if(ObjectUtils.isEmpty(commonWordsTreeSoid)){
            buildActionWarn(actionResult, "常用语树形分类标识不能为空");
        }
        if(CollectionUtils.isEmpty(compositeInstanceSoids)){
            buildActionWarn(actionResult, "常用语标识不能为空");
        }
        knwCompositeInstanceMapper.updateKnwCompositeInstance(compositeInstanceSoids,commonWordsTreeSoid,status);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    /**
     * @param vo
     * @return
     */
    @Override
    public ActionResult addKnwComposite(KnwCompositeTmpVo vo) throws Exception {
        ActionResult actionResult = new ActionResult();
        if (vo != null) {
            if (vo.getListKnwCommonWordsTree() != null
                    && vo.getListKnwCommonWordsTree().size() > 0 ) {
                for (KnwCommonWordsTree kcwt : vo.getListKnwCommonWordsTree()) {
                    knwCommonWordsTreeMapper.insertSelective(kcwt);
                    soidService.insertOid(kcwt.getCommonWordsTreeSoid(), 1);
                }
            }

            if (vo.getListKnwCompositeInstance() != null
                    && vo.getListKnwCompositeInstance().size() > 0 ) {
                for (KnwCompositeInstance kci : vo.getListKnwCompositeInstance()) {
                    knwCompositeInstanceMapper.insertSelective(kci);
                    soidService.insertOid(kci.getCompositeInstanceSoid(), 1);
                }
            }


            if (vo.getListKnwCompositeInstanceShortcut() != null
                    && vo.getListKnwCompositeInstanceShortcut().size() > 0 ) {
                for (KnwCompositeInstanceShortcut kcis : vo.getListKnwCompositeInstanceShortcut()) {
                    knwCompositeInstanceShortcutMapper.insertSelective(kcis);
                }
            }


            if (vo.getListKnwNarrativeBlock() != null
                    && vo.getListKnwNarrativeBlock().size() > 0 ) {
                for (KnwNarrativeBlock knb : vo.getListKnwNarrativeBlock()) {
                    knwNarrativeBlockMapper.addKnwNarrativeBlock(knb);
                }
            }
        }
        buildActionSuccess(actionResult);
        return actionResult;
    }


    private void addNarrativeBlock(KnwCompositeInstanceVo knwCompositeInstanceVo, Long soid, Integer type){
        KnwNarrativeBlock block = new KnwNarrativeBlock();
        if (type == THREE){
            //TODO type=3 代表删除
            block.setUpdateUser(knwCompositeInstanceVo.getCreator());
            block.setUpdateDate(new Date());
            block.setIsDelete((long) ONE);
            knwNarrativeBlockMapper.deteleKnwNarrativeBlock(block);
        }else {
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.isBlank(knwCompositeInstanceVo.getUsContent())){
                map.put("usContent", "");
            }else {
                map.put("usContent", knwCompositeInstanceVo.getUsContent());
            }
            if (StringUtils.isBlank(knwCompositeInstanceVo.getUsDiagnosis())){
                map.put("usDiagnosis", "");
            }else {
                map.put("usDiagnosis", knwCompositeInstanceVo.getUsDiagnosis());
            }
            JSONObject json = new JSONObject(map);
            block.setNarrativeBlock(json.toString());
            block.setCompositeInstanceSoid(soid);
            switch (type){
                //TODO 新增
                case ONE:
                    block.setNarrativeBlockSoid(soidService.getSoid());
                    block.setCreate(knwCompositeInstanceVo.getCreator());
                    block.setIsDelete(IS_DELETE);
                    block.setCreateDate(new Date());
                    knwNarrativeBlockMapper.addKnwNarrativeBlock(block);
                    break;
                //TODO 修改
                default :
                    block.setUpdateUser(knwCompositeInstanceVo.getCreator());
                    block.setUpdateDate(new Date());
                    knwNarrativeBlockMapper.updateKnwNarrativeBlock(block);
                    break;
            }
        }
    }
}
